package com.csdj.server.config;

import com.csdj.server.pojo.Admin;
import com.csdj.server.service.IAdminService;
import com.csdj.server.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @ClassName: SecurityConfig
 * @Author: ZouLi
 * @Description:
 * @Date: 2022/12/14 8:59
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private IAdminService adminService;

    /**
     * 注入 RoleService
     **/
    @Autowired
    private IRoleService roleServiceImpl;

    /**
     * 注入 CustomUrlDecisionManager
     **/
    @Autowired
    private CustomUrlDecisionManager customUrlDecisionManager;

    /**
     * 注入 CustomFilter
     **/
    @Autowired
    private CustomFilter customFilter;

    /**
     * @Description: 密码加密
     * @Param []
     * @Return org.springframework.security.crypto.password.PasswordEncoder
     * @Throws
     **/
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Override
    @Bean
    protected UserDetailsService userDetailsService() {
        // 实现UserDetailsService
        return username -> {
            Admin user = adminService.getUserByUserName(username);
            if (null != user){
                user.setRoles(roleServiceImpl.getRolesByUserId(user.getId()));
                return user;
            }
            throw new UsernameNotFoundException("用户名或密码错误！");
        };
    }

    /**
     * @Description: 自定义登录逻辑添加到security中
     * @Param [auth]
     * @Return void
     * @Throws
     **/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    /**
     * @Description: 配置security地址放行
     * @Param [http]
     * @Return void
     * @Throws
     **/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                // session 进行关闭
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 设置放行的地址
                .authorizeRequests()
                .antMatchers("/login", "logout")
                .permitAll()
                // 所有的请求必须通过认证
                .anyRequest()
                .authenticated()
                // 配置动态权限 配置 url菜单那些角色能访问
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O obj) {
                        obj.setAccessDecisionManager(customUrlDecisionManager);
                        obj.setSecurityMetadataSource(customFilter);
                        return obj;
                    }
                })
                .and()
                // 关闭缓存
                .headers()
                .cacheControl();
        // 登录授权过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        // 添加自定义未授权和未登录结果返回
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //放行静态资源
        web.ignoring().antMatchers(
                "/login",
                "/logout",
                "/ws/**",
                "/css/**",
                "/js/**",
                "/index.html",
                "/favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/captcha");
    }
}
